package io.plus.interactive.utils;

import drds.common.$;
import io.plus.interactive.AsynchronousSocketChannelContext;
import io.plus.interactive.Io;
import io.plus.interactive.task.CloseCode;
import lombok.extern.slf4j.Slf4j;


@Slf4j
public class IoUtils {


    public static boolean check(AsynchronousSocketChannelContext asynchronousSocketChannelContext) {
        if (asynchronousSocketChannelContext.isWaitingClose) {
            return false;
        }
        Boolean open = null;
        if (asynchronousSocketChannelContext.asynchronousSocketChannel == null) {//
            log.error("{}, 请检查此异常, asynchronousSocketChannel is null, isClosed:{}, isRemoved:{}, {} ",//
                    asynchronousSocketChannelContext,//
                    asynchronousSocketChannelContext.isClosed,//
                    asynchronousSocketChannelContext.isRemoved,//
                    $.getStackTrace());//
            return false;
        } else {
            open = asynchronousSocketChannelContext.asynchronousSocketChannel.isOpen();
            if (open) {
                if (asynchronousSocketChannelContext.isClosed || asynchronousSocketChannelContext.isRemoved) {
                    log.info("{}, isopen:{}, isClosed:{}, isRemoved:{}", asynchronousSocketChannelContext, open, asynchronousSocketChannelContext.isClosed, asynchronousSocketChannelContext.isRemoved);
                    try {
                        Io.close(asynchronousSocketChannelContext,
                                "asynchronousSocketChannel is open, but clientChannelContext isClosed: " + asynchronousSocketChannelContext.isClosed + ", isRemoved: " + asynchronousSocketChannelContext.isRemoved, CloseCode.CHANNEL_NOT_OPEN);
                    } catch (Throwable e) {
                        log.error(e.toString(), e);
                    }
                    return false;
                } else {
                    return true;
                }

            } else {
                log.info("{}, 可能对方关闭了连接, isopen:{}, isClosed:{}, isRemoved:{}", asynchronousSocketChannelContext, open, asynchronousSocketChannelContext.isClosed, asynchronousSocketChannelContext.isRemoved);
                Io.close(asynchronousSocketChannelContext, "asynchronousSocketChannel is not open, 可能对方关闭了连接", CloseCode.CHANNEL_NOT_OPEN);
                return false;
            }

        }


    }

}
